﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using FlanProjectData.Helpers;
using Microsoft.Xna.Framework;
using FlanProjectData.Managers;
using Microsoft.Xna.Framework.Content;

namespace FlanProject.ScreenMenu
{
	public class PopupComponent : InterfaceScreen
	{
		private static Logger logger = new Logger("PopupComponent",  Log_Type.DEBUG);

		#region Attributs
		
		private string message;								//Contain de complete message to be draw
		private SpriteFont font;							//Use for define the font size
		private List<string> lstMsg = new List<string>();	//Contain list of msg whose will be draw in popup
		private Rectangle zone = new Rectangle();			//Popup size & position in the windows
		private Vector2 fontDimension;
		private int rowCount;
		private int charCount;
		public Color BackgroundColor { get; set; }
		private Color foregroundColor;
		public Color ForegroundColor
		{
			get { return foregroundColor; }
			set
			{
				this.foregroundColor = value;
				if(lstMenuEntryUnselectable.Count>0)
					this.lstMenuEntryUnselectable.ElementAt(0).color = this.foregroundColor;
			}
		}

		#endregion

		#region Constants

		// relative to the rectangle (ZONE)
		// TODO Dynamic it ?
		// margin equals 5px in
		private const int leftMargin = 5;
		private const int rightMargin = 5;
		private const int topMargin = 5;
		private const int bottomMargin = 5;

		private const string fontLocation = @"Sprites\Fonts\menufont";

		#endregion

		public PopupComponent(string fulltext, int rowInPopup)
		{
			logger.Debug("Instanciation d'un popup");
			this.message = fulltext + " ";
			this.rowCount = rowInPopup;
			this.zone.X = 100;
			this.zone.Y = 100;
			this.zone.Width = windowsWidth - rightMargin;
			this.zone.Height = windowsHeight - bottomMargin;
		}

		public PopupComponent(string fulltext, int rowInPopup, Vector2 pos)
		{
			logger.Debug("Instanciation d'un popup avec Position");
			this.zone.X = (int)pos.X;
			this.zone.Y = (int)pos.Y;
			this.zone.Width = windowsWidth - (int)pos.X;
			this.zone.Height = windowsHeight - (int)pos.Y;
			this.message = fulltext + " ";
			this.rowCount = rowInPopup;
		}

		public PopupComponent(string fulltext, Rectangle popDimension)
		{
			logger.Debug("Instanciation d'un popup avec une taille");
			this.message = fulltext + " ";
			this.rowCount = 0;
			this.zone = popDimension;
		}

		public override void Draw(SpriteBatch sb)
		{
			logger.Debug("Draw");

			if (this.Visible)
			{
				// Generate the popup background
				var t = new Texture2D(sb.GraphicsDevice, 1, 1);
				t.SetData(new Color[] { Color.White });
				this.background = t;

				sb.Draw(this.background, zone, this.BackgroundColor);
			}

			base.Draw(sb);
		}

		public override void HandleInput()
		{
			if(InputManager.IsActionTriggered(InputManager.Action.Exit))
			{
				logger.Debug("Demande de fermeture du popup");
				this.IsExiting = true;
			}
			else if (InputManager.IsActionTriggered(InputManager.Action.Ok))
			{
				// Console.WriteLine("Input");

				lstMsg.RemoveAt(0);
				if (lstMsg.Count() != 0)
				{
					logger.Debug("The rest of the message");
					this.lstMenuEntryUnselectable[0].message = lstMsg[0];
				}
				else
				{
					logger.Debug("Popup will be close");
					this.IsExiting = true;
				}
			}
		}

		public override void Update()
		{
			base.Update();
		}

		public override void LoadContent(ContentManager cm)
		{
			this.ForegroundColor = Color.Black;
			this.BackgroundColor = Color.ForestGreen;

			this.font = cm.Load<SpriteFont>(fontLocation);
			this.fontDimension = font.MeasureString("M");
			this.createListOfMessage();
			this.defineThePopupDimension();	// calculate the popup dimension

			//Create new menuentry to draw the first text
			this.lstMenuEntryUnselectable.Add(new MenuEntry(
				lstMsg[0], new Vector2(this.zone.X + leftMargin, this.zone.Y + topMargin), true, this.ForegroundColor, 1)); 

			base.LoadContent(cm);
		}

		protected void createListOfMessage()
		{
			logger.Debug("CreateListOfMessage");
			// Vars
			int rectEfficientWidth = this.zone.Width - leftMargin - rightMargin;
			int rectEfficientHeigth = this.zone.Height - topMargin - bottomMargin;
			int it = 0;
			string tmp = "";

			this.charCount = rectEfficientWidth / (int)fontDimension.X;
			if (rowCount == 0)
			{
				this.rowCount = (int)(rectEfficientHeigth / (int)this.fontDimension.Y);
			}

			logger.Debug("this.charCount : " + this.charCount);
			logger.Debug("this.rowCount : " + this.rowCount);

			// Generate list of message
            bool hasN = false;
            if (message.IndexOf('\n', 0) != -1)
            {
                hasN = true;
            }
			while (message.Length > this.charCount)
			{
				//Last line of the popup
				if (it % this.rowCount == 0 && tmp != "")
				{
					lstMsg.Add(tmp);
					tmp = "";
				}

				int currentIndex = 0;
				bool stop = false;

				// check spaces in the string
                bool word = false;
                
                while (!stop)
				{

                    if (hasN == true)
                    {
                        int val = message.IndexOf('\n', currentIndex) - message.IndexOf(' ', currentIndex);
                        if (val < 0)
                        {
                            stop = true;
                        }
                    }
                    if (message.IndexOf(' ', currentIndex) > this.charCount)
                    {
                        word = true;
                        stop = true; 
                    }
					else if (currentIndex > message.Length) 
                    { 
                        stop = true; 
                    }
					else {
                        currentIndex = message.IndexOf(' ', currentIndex) + 1;
                    }

                    
				}
                
                string add = "";
                if (word == true)
                {
                    add = "\n";
                }

                tmp += message.Substring(0, currentIndex) + add;
				message = message.Remove(0, currentIndex);
				it++;
			}
			// For redimensione the popup
			if (it < this.rowCount) { this.rowCount = it+1; }

			lstMsg.Add(tmp + message);
		}

		protected void defineThePopupDimension()
		{
			if (zone == null)
			{
				this.zone = new Rectangle();
			}
			this.zone.Height = this.rowCount * (int)fontDimension.Y;
			this.zone.Width = this.charCount * (int)fontDimension.X;
		}
	}
}
